/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.pingan.mobilegw.biz.shared.router;

import com.pingan.mobilegw.adapterservice.ResultEnum;
import com.pingan.mobilegw.biz.shared.router.executor.BatchExecutor;
import com.pingan.mobilegw.biz.shared.router.post.PostProcessor;
import com.pingan.mobilegw.core.model.GatewayRequest;
import com.pingan.mobilegw.core.model.GatewayResponse;
import com.pingan.mobilegw.core.model.enums.BatchTypeEnum;
import com.pingan.mobilegw.core.model.exception.MgwException;
import com.pingan.mobilegw.core.model.request.BatchRequestBody;
import com.pingan.mobilegw.core.service.util.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Map;

/**
 * 多请求服务路由器
 * 
 * @author jiadao
 * @version $Id: BatchServiceRouterImpl.java, v 0.1 2013-4-12 下午7:17:40 jiadao Exp $
 */
public class BatchServiceRouterImpl implements ServiceRouter {

    /** logger */
    private static final Log logger = LogFactory
                                                         .getLog(BatchServiceRouterImpl.class);

    /** 批量处理器 */
    private Map<BatchTypeEnum, BatchExecutor> batchExecutorMap;

    /** 后置处理器 */
    private PostProcessor                     refreshTokenPostProcessor;


    @Override
    public GatewayResponse processRoute(GatewayRequest request) {

        try {

            BatchRequestBody multiRequestBody = (BatchRequestBody) request.getRequestBody();
            BatchExecutor executor = batchExecutorMap.get(multiRequestBody.getBatchType());
            executor.execute(request, null);

            refreshTokenPostProcessor.execute(request, null);

            return null;

        } catch (MgwException e) {
            logger.warn("无线网关路由错误," + e);
            return ResponseUtil.buildErrorResponse(e);
        } catch (Exception e) {
            logger.error("服务路由未知异常", e);
            return ResponseUtil.buildErrorResponse(ResultEnum.UnknowError);
        }

    }

    /**
     * Setter method for property <tt>batchExecutorMap</tt>.
     * 
     * @param batchExecutorMap value to be assigned to property batchExecutorMap
     */
    public void setBatchExecutorMap(Map<BatchTypeEnum, BatchExecutor> batchExecutorMap) {
        this.batchExecutorMap = batchExecutorMap;
    }

    /**
     * Setter method for property <tt>refreshTokenPostProcessor</tt>.
     * 
     * @param refreshTokenPostProcessor value to be assigned to property refreshTokenPostProcessor
     */
    public void setRefreshTokenPostProcessor(PostProcessor refreshTokenPostProcessor) {
        this.refreshTokenPostProcessor = refreshTokenPostProcessor;
    }

}
